package net.lbtech.util;

import com.alibaba.fastjson.JSONObject;
import net.lbtech.util.exception.WeatherException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * Created by Administrator on 2016/11/22 0022.
 */
public class WeatherUtil {
    protected static Logger logger = LoggerFactory.getLogger(WeatherUtil.class);

    public static JSONObject getWeatherAll(String cityname){
        HashMap map = new HashMap();
        map.put("key", "8f50b53a5ff8c3bd5239c1001b6b74a7");
        map.put("cityname", cityname);
        map.put("dtype", "json");
        JSONObject json = HttpUtil.postAsJson(map,"http://op.juhe.cn/onebox/weather/query");
//        logger.debug(json.toJSONString());
        return json;
    }

    public static JSONObject getRedisWeatherAll(String cityname){
        JSONObject json = RedisUtil.getJson(cityname);
        return json;
    }

    //获取一个天气而已
    public static String getWeatherInfo(String cityname) throws WeatherException {
        JSONObject weatherJson = getRedisWeatherAll(cityname);
        String weatherInfo;
        if(0 == weatherJson.getIntValue("error_code")){
            weatherInfo = weatherJson.getJSONObject("result")
                    .getJSONObject("data")
                    .getJSONObject("realtime")
                    .getJSONObject("weather")
                    .getString("info");
        }else {
            throw new WeatherException("城市名："+cityname+"|||"+weatherJson.toJSONString());
        }
        return weatherInfo;
    }


    /**
     * 获取室外PM2.5，温度，湿度，污染等级。
     * @param cityname
     * @return humidity 湿度；pm25室外 PM2.5；temperature 湿度
     */
    public static HashMap getOutDoorWeather(String cityname) throws WeatherException {
        JSONObject weatherJsonR = getRedisWeatherAll(cityname);
        HashMap hm = new HashMap();
        JSONObject dataJson = weatherJsonR.getJSONObject("result").getJSONObject("data");
        JSONObject weatherJson = dataJson.getJSONObject("realtime").getJSONObject("weather");
        //pm2.5
        int pm25 = dataJson.getJSONObject("pm25").getJSONObject("pm25").getInteger("pm25");
        //空气污染等级
        int level = dataJson.getJSONObject("pm25").getJSONObject("pm25").getInteger("level");
        //温度
        int temperature = weatherJson.getInteger("temperature");
        //湿度
        int humidity = weatherJson.getInteger("humidity");
        //天气
        String weather = weatherJson.getString("img");
        hm.put("pm25",pm25+"");
        hm.put("temperature",temperature+"");
        hm.put("humidity",humidity+"");
        hm.put("level",level+"");
        hm.put("weather",weather+"");
        logger.debug(hm.toString());
        return hm;
    }



}
